package com.ruoyi.hyg.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.hyg.domain.DailyPractice;
import com.ruoyi.hyg.service.IDailyPracticeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

@RestController
@RequestMapping("/hyg/practice")
public class DailyPracticeController extends BaseController {
    @Autowired
    private IDailyPracticeService dailyPracticeService;
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:list')")
    @GetMapping("/list")
    public TableDataInfo list(DailyPractice dailyPractice) {
        startPage();
        List<DailyPractice> list = dailyPracticeService.selectDailyPracticeList(dailyPractice);
        return getDataTable(list); // 确保返回的数据包含 rank 和 pointsAwarded
    }
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:export')")
    @Log(title = "一日一练记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DailyPractice dailyPractice) {
        List<DailyPractice> list = dailyPracticeService.selectDailyPracticeList(dailyPractice);
        ExcelUtil<DailyPractice> util = new ExcelUtil<>(DailyPractice.class);
        util.exportExcel(response, list, "一日一练记录数据");
    }
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(dailyPracticeService.selectDailyPracticeById(id));
    }
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:add')")
    @Log(title = "一日一练记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DailyPractice dailyPractice) {
        return toAjax(dailyPracticeService.insertDailyPractice(dailyPractice));
    }
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:edit')")
    @Log(title = "一日一练记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DailyPractice dailyPractice) {
        return toAjax(dailyPracticeService.updateDailyPractice(dailyPractice));
    }
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:remove')")
    @Log(title = "一日一练记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dailyPracticeService.deleteDailyPracticeByIds(ids));
    }
    
    @GetMapping("/user/{userId}")
    public AjaxResult getUserPracticeData(@PathVariable Long userId) {
        return success(dailyPracticeService.selectDailyPracticeList(
                new DailyPractice().setUserId(userId)
        ));
    }
    
    @GetMapping("/user/{userId}/totalQuestions")
    public AjaxResult getTotalQuestions(@PathVariable Long userId) {
        return success(dailyPracticeService.sumQuestionsByUser(userId));
    }
    
    @PreAuthorize("@ss.hasPermi('hyg:practice:ranking')")
    @Log(title = "一日一练记录", businessType = BusinessType.OTHER)
    @PostMapping("/processRanking")
    public AjaxResult processRanking(@RequestParam Date practiceDate) {
        dailyPracticeService.processDailyRankingAndRewards(practiceDate);
        return success("每日排名处理完成，积分奖励已发放");
    }
    
    @GetMapping("/ranking")
    public TableDataInfo getDailyRanking(@RequestParam Date practiceDate, 
                                       @RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "50") Integer pageSize) {
        startPage(pageNum, pageSize);
        // 使用支持分页的方法，避免SQL语法错误
        List<DailyPractice> list = dailyPracticeService.selectDailyRankingForDisplay(practiceDate);
        return getDataTable(list);
    }
    
    private void startPage(Integer pageNum, Integer pageSize) {
    }
    
    // 获取用户累计练习天数
    @GetMapping("/user/{userId}/totalDays")
    public AjaxResult getUserTotalPracticeDays(@PathVariable Long userId) {
        Integer totalDays = dailyPracticeService.getUserTotalPracticeDays(userId);
        return success(totalDays);
    }
}